<?php

/**
 * Contains the Haversine function to compute distance between two points.
 *
 * PHP Version 5
 *
 * @category BuyLocal
 * @package  BuyLocal
 * @author   Kevin Fodness <kevin.fodness@gmail.com>
 * @author   Mike Pennisi <mpennisi@andrew.cmu.edu>
 * @author   Aaron Ryden <aryden@gmail.com>
 * @author   Spencer Hakim <hakims@rpi.edu>
 * @license  http://opensource.org/licenses/gpl-license.php GNU Public License
 * @link     http://code.google.com/p/buylocalopensourcerensselaer/
 */

/**
 * The Haversine function to compute distance between two points.
 *
 * @param float  $lat1 The latitude of the first point in degrees.
 * @param float  $lng1 The longitude of the first point in degrees.
 * @param float  $lat2 The latitude of the second point in degrees.
 * @param float  $lng2 The longitude of the second point in degrees.
 * @param string $unit The unit of distance measurement (km or mi).
 *
 * @access public
 * @return float  The distance, in whatever unit was chosen.
 */
function haversine($lat1, $lng1, $lat2, $lng2, $unit = 'mi')
{
    /** Earth's mean radius. */
    $r = ($unit == 'km') ? 6371 : 3958.75587;
    
    /** Convert degrees to radians using pre-computed M_PI/180 */
    $lat1 *= 0.01745329251994329576923690768489;
    $lat2 *= 0.01745329251994329576923690768489;
    $lng1 *= 0.01745329251994329576923690768489;
    $lng2 *= 0.01745329251994329576923690768489;
    
    /** Gets the difference between latitude and longitude points. */
    $deltaLat = $lat2 - $lat1;
    $deltaLng = $lng2 - $lng1;
    
    /** Computes and returns the distance using the Haversine formula. */
    $a = sin($deltaLat / 2) * sin($deltaLat / 2)
        + cos($lat1) * cos($lat2)
        * sin($deltaLng / 2) * sin($deltaLng / 2);
    $c = 2 * atan2(sqrt($a), sqrt(1 - $a));
    $d = $r * $c;
    return $d;
}

?>